<template>
  <div>
    <el-dialog :title="`PH_CHA`" v-dialogDrag :visible.sync="isShowCHA" :close-on-click-modal="false" :before-close="handleClose"
      :width="screenWidth > 1310 ? '55%' : '70%'">
      <el-form :model="formData" label-width="70px" ref="ruleForm" size="small" :rules="rules" :hide-required-asterisk="true">
        <el-row :gutter="24" class="gz-form-row">
          
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.isAuto">{{$t('common.auto_start')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="9" :md="9" :lg="9" :xl="6">
            <el-form-item :label="$t('common.start_delay')" label-width="70px" class="inputPadding">
              <el-input type="number" v-model="formData.delayTime">
                <template slot="append">min</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="4" :md="4" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.mode">{{$t('common.operation_signature')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <el-col :xs="5" :sm="5" :md="5" :lg="3" :xl="3">
            <el-form-item label="" label-width="0">
              <el-checkbox v-model="formData.checks">{{$t('common.review_confirmation')}}</el-checkbox>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
                        <el-form-item :label="$t('basic.stage_name')" prop="phaseDesc">
                            <el-input disabled v-model="formData.phaseDesc" placeholder="" clearable></el-input>
                        </el-form-item>
                    </el-col> -->

        </el-row>
        <el-row :gutter="24">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('basic.material')" prop="itemId">
              <el-select v-model="formData.itemId" remote filterable :remote-method="remoteMethodMaterial" placeholder=""
                v-el-select-loadmore="loadMoreMaterialFun" clearable @clear="clearMaterial" @change="changeItemId">
                <el-option v-for="(item,index) in materialList" :key="index" :label="item.fid" :value="item.fid"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('common.weight')" prop="qty">
              <el-input type="number" v-enterNumber2 v-model="formData.qty" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('basic.company')">
              <el-input v-model="formData.uom" disabled placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('common.upper_limit')" prop="hi">
              <el-input type="number" v-enterNumber2 v-model="formData.hi" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <el-form-item :label="$t('common.lower_limit')" prop="lo">
              <el-input type="number" v-enterNumber2 v-model="formData.lo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item label="" label-width="0">
              <!-- <el-checkbox v-model="formData.confirm"> -->
              <p style="font-weight: bold">{{$t('dialog.confirm_info')}}</p>
              <!-- </el-checkbox> -->
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('common.operating_instructions')">
              <el-input type="textarea" rows="3" v-model="formData.guideInfo" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24">
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24">
            <el-form-item :label="$t('basic.remarks')">
              <el-input type="textarea" rows="3" v-model="formData.flastModifyComment" placeholder="" clearable></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="small" :loading="loading" :disabled="isreadOnly"
          @click="handleConfirm('ruleForm')">{{ $t("common.preservation") }}</el-button>
        <el-button @click="handleClose()" size="small">{{ $t("common.cancel") }}</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { configure } from "@/api/configure"
import { formula } from "@/api/formula"
export default {
  props: {
    isShowCHA: Boolean,
    tdIndex: Number,
    stepObj: Object,
    isreadOnly: Boolean
  },
  data () {
    let HiFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(this.formData.qty) > parseFloat(value)) {
          callback(new Error('物料上限不能小于物料数量'));
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    let LoFn = (rule, value, callback) => {
      if (value) {
        if (parseFloat(value) > parseFloat(this.formData.qty)) {
          callback(new Error('物料下限不能大于物料数量'));
        } else if (this.formData.hi) {
          if (parseFloat(value) > parseFloat(this.formData.hi)) {
            callback(new Error('物料下限不能大于物料上限'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      } else {
        callback();
      }
    }
    return {
      screenWidth: document.body.clientWidth,
      formData: {
        stepDesc: "",
        isActive: false,
        isAuto: false,
        itemId: "",
        qty: "",
        uom: "",
        confirm: "",
        flastModifyComment: "",
        guideInfo: "",
        phaseDesc: "自动加料",
        hi: "",
        lo: "",
        delayTime: "",
        mode: false,
        checks: false,
        stepSort: 0,
      },
      stepId: "",
      rules: {
        itemId: [{ required: true, message: '请选择物料名称', trigger: 'change' }],
        qty: [{ required: true, message: '请输入数量', trigger: 'blur' }],
        hi: [{ validator: HiFn, trigger: 'blur' }],
        lo: [{ validator: LoFn, trigger: 'blur' }]
      },
      loading: false,
      pager: {
        pageNum: 1,
        pageSize: 10,
      },
      keyword: "",
      materialList: [],
      stepLoading: false,
      title: "添加",
      phaseLoading: false,
      phaseId: ""
    }
  },
  watch: {
    screenWidth (val) {
      this.screenWidth = Number(val)
    },
    isShowCHA (val) {
      if (val) {
        console.log(this.stepObj)
        this.formData.stepDesc = this.stepObj.stepDesc
        this.formData.isActive = this.stepObj.isActive == 1 ? true : false
        this.formData.seqNo = this.stepObj.seqNo
        this.formData.phaseDesc = this.stepObj.texts

        this.formData.stepNo = this.tdIndex
        this.formData.mode = this.stepObj.mode == 1 ? true : false
        this.formData.checks = this.stepObj.checks == 1 ? true : false
        this.formData.delayTime = this.stepObj.delayTime

        if (this.stepObj.fid || this.stepObj.fId) {
          this.phaseAutoFind()
        }
        this.formData.isAuto = this.stepObj.isAuto == 1 ? true : false
        this.phaseId = this.stepObj.fid || this.stepObj.fId
        this.formData.confirm = this.stepObj.confirm == 1 ? true : false
        this.formData.flastModifyComment = this.stepObj.flastModifyComment
        this.formData.guideInfo = this.stepObj.guideInfo
      } else {
        for (let key in this.formData) {
          this.formData[key] = ""
        }
        this.title = "添加"
        this.stepId = ""
      }
      this.formData.stepSort = this.stepObj.stepSort ?? 0
    }
  },
  mounted () {
    const that = this
    window.addEventListener('resize', function () {
      that.screenWidth = document.body.offsetWidth;
    })
  },
  created () {
    console.info('111')
    this.getItemList()
  },
  methods: {
    phaseAutoFind () {
      const param = {
        phaseId: this.stepObj.fid,
      }
      formula.phaseAutoList(param).then(res => {
        if (res.code == 200) {
          this.list = res.data.rows
          if (res.data.rows.length > 0) {
            this.title = "编辑"
            this.formData.itemId = res.data.rows[0].paraName
            this.formData.qty = res.data.rows[0].target
            this.formData.uom = res.data.rows[0].uom
            this.stepId = res.data.rows[0].fid
            this.formData.hi = res.data.rows[0].hi
            this.formData.lo = res.data.rows[0].lo
          }

        }
      })
    },
    getItemList () {
      const param = {
        className: this.keyword,
        page: this.pager.pageNum,
        size: this.pager.pageSize,
        itemClassVo: {
          consumed: 1
        }
      }
      configure.getItemList(param).then(res => {
        if (res.code == 200) {
          this.materialList = [...this.materialList, ...res.data.rows]
        }
      })
    },
    remoteMethodMaterial (keyword) {
      this.keyword = keyword.trim();
      this.pager.pageNum = 1
      setTimeout(() => {
        this.materialList = []
        this.getItemList()
      }, 200)
    },
    loadMoreMaterialFun () {
      this.pager.pageNum++
      this.getItemList()
    },
    clearMaterial () {
      this.keyword = ""
      this.pager.pageNum = 1
      this.materialList = []
      this.getItemList()
    },
    handleConfirm (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const param = {
            phaseDesc: this.formData.phaseDesc,
            isAuto: this.formData.isAuto == false ? 0 : 1,
            isActive: this.formData.isActive == false ? 0 : 1,
            checks: this.formData.checks == false ? 0 : 1,
            delayTime: this.formData.delayTime,
            operationId: this.stepObj.operationId,
            type: this.stepObj.type,
            confirm: this.formData.confirm == false ? 0 : 1,
            flastModifyComment: this.formData.flastModifyComment,
            guideInfo: this.formData.guideInfo,
            mode: this.formData.mode == false ? 0 : 1,
            seqNo: this.stepObj.seqNo,
            stepNo: this.stepObj.stepNo,
            phaseCode: this.stepObj.phaseCode,
            serialNo: this.stepObj.serialNo,
          }
          if (this.phaseId) {
            param.fid = this.phaseId
          }
          this.loading = true
          formula.phaseAdd(param).then(res => {
            if (res.code == 200) {
              this.handleSubmit()
            } else {
              this.$message.error(res.msg);
            }
          })
        }
      })
    },
    handleSubmit () {
      const param = [{
        paraName: this.formData.itemId,
        uom: this.formData.uom,
        target: this.formData.qty,
        phaseDesc: this.formData.phaseDesc,
        phaseId: this.stepObj.fid,
        lo: this.formData.lo,
        hi: this.formData.hi,
        stepSort: this.formData.stepSort,
      }]
      if (this.title == "编辑") {
        param[0].fid = this.stepId
      }
      formula.phaseAutoAdd(param, this.title).then(res => {
        this.loading = false
        if (res.code == 200) {
          this.$message({ duration: 1000, type: 'success', message: '保存成功!' });
          let obj = {
            mode: this.stepObj.mode,
            isAuto: this.formData.isAuto == false ? 0 : 1,
            isActive: this.formData.isActive == false ? 0 : 1,
            operationId: this.stepObj.operationId,
            seqNo: this.stepObj.seqNo,
            serialNo: this.stepObj.serialNo,
            text: this.stepObj.phaseDesc
          }
          this.$emit("uptionData", obj)
          this.$emit("closePH", "CHA")
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    handleClose () {
      this.$refs["ruleForm"].resetFields();
      this.$emit("closePH", "CHA")
    },
    changeCheck (val) {
      this.$forceUpdate()
    },
    changeItemId (val) {
      this.formData.uom = this.materialList.find(item => item.fid == val).uomId
    },
  },
}
</script>
